package com.itic.market.mobile.base;



import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;

import com.itic.appbase.applications.mail.Mail;
import com.itic.appbase.applications.sys.syssetting.service.SysSettingService;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.utils.CalendarHelper;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.HttpRequestUtils;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.NumberStringHelper;
import com.itic.appbase.framework.utils.RandomOrderNumHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.market.system.synctgw.persistence.model.SyncTgw;
import com.itic.market.system.markettoken.persistence.model.MarketToken;
import com.itic.market.system.markettoken.service.MarketTokenService;
import com.itic.market.system.phonecode.persistence.model.PhoneCode;
import com.itic.market.system.phonecode.persistence.model.PhoneCodeExample;
import com.itic.market.system.phonecode.service.PhoneCodeService;
import com.itic.market.system.product.persistence.model.Product;
import com.itic.market.system.product.service.ProductService;
import com.itic.market.system.productjd.service.ProductJdService;
import com.itic.market.system.productjdstatis.persistence.model.ProductJdStatis;
import com.itic.market.system.productjdstatis.persistence.model.ProductJdStatisExample;
import com.itic.market.system.productjdstatis.service.ProductJdStatisService;
import com.itic.market.system.synctgw.service.SyncTgwService;
import com.itic.market.system.user.persistence.model.MarketUser;
import com.itic.market.system.user.persistence.model.MarketUserExample;
import com.itic.market.system.user.persistence.model.MarketUserExample.Criteria;
import com.itic.market.system.user.service.MarketUserService;

import net.sf.json.JSONObject;


public class BaseMobileInterface
     extends BaseController {
	protected static String Url = "http://120.55.205.5/webservice/sms.php?method=Submit";//发送短信的URL
	@Autowired
    protected SysSettingService sysSettingService;
	@Autowired
	protected MarketUserService marketUserService;
	@Autowired
	protected MarketTokenService marketTokenService;
	@Autowired
	protected PhoneCodeService phoneCodeService;
	@Autowired
	protected SyncTgwService syncTgwService;
	@Autowired
	protected ProductJdStatisService productJdStaticsService;
	@Autowired
	protected ProductJdService productJdService;
	
	protected static final String ORG_CODE = "0";//京券联盟组织机构代码
	//protected static final String ORG_CODE = "00083155863";//京券联盟组织机构代码
	protected static final String CREATE_USER = "0";
	
	//接口返回键
    protected static final String RESULT = "result";
    protected static final String DATA = "data";
    protected static final String ERROR_CODE = "errorCode";
    protected static final String ERROR_MSG = "errorMsg";
    //接口返回值
    protected static final String SUCCESS = "success";
    protected static final String LOGIN = "login";
    protected static final String FAIL = "fail";
    
    protected static final String MARKET_USER_PRODUCT_COMMON_URL = "http://www.jhjvip.cn:8080/mall/mobile/product/detail?marketUserProductId=";//当系统 没有设置 推广URL 地址的时候使用
    protected static final String MARKET_USER_STORE_COMMON_URL = "http://www.jhjvip.cn:8080/market/mobile/store/index?userId=";
    
    protected static final String SUCCESS_ERROR_CODE = "0";//服务器异常
    protected static final String SERVER_ERROR_CODE = "1";//服务器异常
    protected static final String PARAM_ERROR_CODE = "2";//参数不正确
    protected static final String LOGIN_ERROR_CODE = "3";//用户未登入
    protected static final String PHONE_CODE_ERROR_CODE = "4";//验证码无效
    protected static final String PRODUCT_EMPTY_ERROR_CODE = "5";//验证码无效
    protected static final String TOKEN_ERROR_CODE = "6";//TOKEN无效
    protected static final String OPENID_ERROR_CODE = "7";//OPENID无效
    protected static final String UNIONID_ERROR_CODE = "8";//UNIONID 无效 
    protected static final String INVITING_ERROR_CODE ="9";//用户邀请码无效
    protected static final String STORE_CODE_ERROR_CODE = "10";//店铺的代码无效
    protected static final String PRODUCT_ID_ERROR_CODE = "11";//商品ID无效
    protected static final String NOTICE_ID_ERROR_CODE = "12";//商品ID无效
    protected static final String LESS_MONEY_ERROR_CODE = "13";//
    protected static final String OPENID_EXIST_ERROR_CODE = "14";//
    protected static final String PHONE_NULL_ERROR_CODE = "15";//
    protected static final String PHONE_USED_ERROR_CODE = "16";//
    protected static final String JD_PRODUCT_EXPIRED_ERROR_CODE = "17";//
    protected static final String PRODUCT_EXPIRED_ERROR_CODE = "18";//
    protected static final String WEIXIN_AUTH_ERROR_CODE = "20";
    protected static final String MUST_ONE_MONEY_ERROR_CODE = "21";
    protected static final String WEIXIN_BATCH_ERROR_CODE = "22";
    protected static final String YUN_NOT_ERROR_CODE = "23";
    
    
    protected static final String SUCCESS_ERROR_MSG = "请求成功！";//服务器异常
    protected static final String SERVER_ERROR_MSG = "服务器繁忙，请重试！";//服务器异常
    protected static final String PARAM_ERROR_MSG = "参数不正确，请检查！";//参数不正确
    protected static final String LOGIN_ERROR_MSG = "登入过期，请重新登入！";//用户未登入
    protected static final String PHONE_CODE_ERROR_MSG = "验证码无效！";//验证码无效
    protected static final String PRODUCT_EMPTY_ERROR_MSG = "商品数量不能为空!";//验证码无效
    protected static final String TOKEN_ERROR_MSG = "token无效!";//验证码无效
    protected static final String OPENID_ERROR_MSG = "openid无效!";//验证码无效
    protected static final String UNIONID_ERROR_MSG = "登入过期，请重新登入！";//验证码无效
    protected static final String INVITING_ERROR_MSG = "邀请码无效！";//注册成为商家的邀请码无效
    protected static final String STORE_CODE_ERROR_MSG = "店铺的代码无效！";//店铺的代码无效
    protected static final String PRODUCT_ID_ERROR_MSG ="商品ID无效！";//商品ID无效
    protected static final String NOTICE_ID_ERROR_MSG ="公告ID无效！";//商品ID无效
    protected static final String LESS_MONEY_ERROR_MSG ="用户金额不足！";//商品ID无效
    protected static final String OPENID_EXIST_ERROR_MSG = "您已入驻过了";
    protected static final String PHONE_NULL_ERROR_MSG = "手机号未注册";
    protected static final String PHONE_USED_ERROR_MSG = "手机号已注册过了";
    protected static final String JD_PRODUCT_EXPIRED_ERROR_MSG = "京东商品已过期！";
    protected static final String PRODUCT_EXPIRED_ERROR_MSG = "友惠商品已过期！";
    protected static final String WEIXIN_AUTH_ERROR_MSG = "需要微信授权登入！";
    protected static final String MUST_ONE_MONEY_ERROR_MSG = "提现金额必段大于1元！";
    protected static final String WEIXIN_BATCH_ERROR_MSG = "未找到批量商品信息！";
    protected static final String YUN_NOT_ERROR_MSG ="你还不是云店主！";
    
    public HttpServletResponse isCrrossDomain( HttpServletResponse response ){
    	//是否允许跨域
    	String isCrrossDomain = sysSettingService.getByKey("IS_CRROSS_DOMAIN");
    	//String isSetCrrossDomain = PropertyGetter.getString("app.is.crross.domain");
    	if( "1".equals( isCrrossDomain ) ){
    		response.setHeader( "Access-Control-Allow-Origin","*" ); 
    	}
    	return response;
    }
    
    public void log( Exception e ){
    	
    }
    
    /**
     * 获取随机TOKEN方法
     */
    public String getToken(){
    	String orderNumber = RandomOrderNumHelper.getOrderNumber();
    	String uuid = IdGen.uuid();
    	return orderNumber + uuid;
    }
    
    /**
     * 获取 Token的过期 时间
     * @param date
     * @return
     */
    public Date getExpiredTimeToken(Date date){
    	String dayStr = "7";//默认TOKEN有效期为7天
    	String daySet =sysSettingService.getByKey("TOKEN_EXPIRED_DAY");
    	if( StringHelper.isNotBlank(daySet) ){
    		dayStr = daySet;
    	}
    	Date dateAfter = CalendarHelper.getDateAfter(date, Integer.parseInt(dayStr));
    	return dateAfter;
    }
    
    /**
     * 获取 验证码的过期 时间
     * @param date
     * @return
     */
    public Date getExpiredTimeCode(Date date){
    	String minuteStr = "5";//默认CODE有效期为5分
    	String minuteSet =sysSettingService.getByKey("CODE_EXPIRED_MINUTE");
    	if( StringHelper.isNotBlank(minuteSet) ){
    		minuteStr = minuteSet;
    	}
    	Date dateAfter = CalendarHelper.getMinuteAfter(date, Integer.parseInt(minuteStr));
    	return dateAfter;
    }
    
    /**
     * 获取当前版本信息
     * @return
     */
    public String getVersionMsg(){
    	String versionStr = "1.0.0";//默认CODE有效期为5分
    	String versionSet =sysSettingService.getByKey("PROJECT_VERSION_IOS");
    	if( StringHelper.isNotBlank(versionSet) ){
    		versionStr = versionSet;
    	}
    	return versionStr;
    }
    
    /**
     * 根据TOKEN获得用户,同时验证token的有效期
     * @return
     */
    public MarketUser getMarketUserByToken( String token ){
    	MarketUser user = null;
    	MarketToken marketTokenByToken = marketTokenService.getMarketTokenByToken(token);
    	if( null != marketTokenByToken ){
    		Date expiredTime = marketTokenByToken.getExpiredTime();
        	Date now = new Date();
        	if( DateHelper.isGreaterDate(expiredTime, now) ){
        		//根据TOKEN里的userId找到相应 的用户
        		String userId = marketTokenByToken.getUserId();
        		user = marketUserService.get(userId);
        	}
    	}
    	return user;
    }
    
    /**
     * 根据用户的OPENID 查找用户
     * @param openid
     * @return
     */
    public MarketUser getMarketUserByOpenid( String openid ){
    	MarketUser user = null;
    	MarketUserExample example = new MarketUserExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	criteria.andOpenidEqualTo(openid);
    	List<MarketUser> list = marketUserService.list(example);
    	if( list.size() > 0 ){
    		user = list.get(0);
    	}
    	return user;
    }
    
    /**
     * 根据用户的UNION ID 查找用户
     * @param openid
     * @return
     */
    public MarketUser getMarketUserByUnionId( String unionId ){
    	MarketUser user = null;
    	MarketUserExample example = new MarketUserExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	criteria.andUnionIdEqualTo(unionId);
    	List<MarketUser> list = marketUserService.list(example);
    	if( list.size() > 0 ){
    		user = list.get(0);
    	}
    	return user;
    }
    
    /**
     * 用户默认的头像地址
     * @return
     */
    public String getDefaultHeadImg(){
    	String defaultImg = sysSettingService.getByKey("USER_DEFAULT_IMG");
    	return defaultImg;
    }
    
    /**
     * 判断用户的手机号码与验证码是否一致，且有效没有过期
     * @param phone
     * @param code
     * @return
     */
    public boolean isPhoneCode( String phone, String code ){
    	boolean result = false;
    	PhoneCodeExample example = new PhoneCodeExample();
    	example.setOrderByClause("expired_time desc");
    	example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andPhoneEqualTo(phone).andCodeEqualTo(code);
    	List<PhoneCode> list = phoneCodeService.list(example);
    	if( list.size() > 0 ){
    		PhoneCode phoneCode = list.get(0);
    		Date expiredTime = phoneCode.getExpiredTime();
    		Date now = new Date();
        	if( DateHelper.isGreaterDate(expiredTime, now) ){
        		result = true;
        	}
    	}
    	return result;
    }
    
    /**
     * 根据邀请码查找店铺
     * @param invitingCode
     * @return
     */
    public MarketUser getMarketUserByInvitingCode( String invitingCode ){
    	MarketUser user = null;
    	MarketUserExample example = new MarketUserExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	criteria.andInvitingCodeEqualTo(invitingCode);
    	List<MarketUser> list = marketUserService.list(example);
    	if( list.size() > 0 ){
    		user = list.get(0);
    	}
    	return user;
    }
    
    
    //获得商品的推广的通用URL信息
    public String getMarketUserCommonUrl(){
    	String result = MARKET_USER_PRODUCT_COMMON_URL;
    	String dbRes = sysSettingService.getByKey("MARKET_USER_PRODUCT_COMMON_URL");
    	if( StringHelper.isNotBlank( dbRes )){
    		result = dbRes;
    	}
    	return result;
    }
    
    public String getMarketStoreCommonUrl(){
    	String result = MARKET_USER_STORE_COMMON_URL;
    	String dbRes = sysSettingService.getByKey("MARKET_USER_STORE_COMMON_URL");
    	if( StringHelper.isNotBlank( dbRes )){
    		result = dbRes;
    	}
    	return result;
    }
    
    public MarketUser getMarketUserByPhone( String phone ){
    	MarketUser user = null;
    	MarketUserExample example = new MarketUserExample();
    	example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andUserPhoneEqualTo(phone);
    	List<MarketUser> list = marketUserService.list(example);
    	if( list.size() > 0 ){
    		user = list.get(0);
    	}
    	return user;
    }
    
    public String sendMassageByHuifa( String telphone ){
    	String result = FAIL;
    	   //产生随机的验证码
        String codeCont = "";
	    Random r = new Random();
	    for(int i=0;i<6;i++){
	    	codeCont += String.valueOf(r.nextInt(10));
	    }
	    
	    PhoneCode phoneCode = new PhoneCode();
		phoneCode.setPhone(telphone);
		phoneCode.setCode(codeCont);
		phoneCode.setExpiredTime(getExpiredTimeCode(new Date()));
		
	    phoneCodeService.add(phoneCode);
		try {
		
		//String Text=URLEncoder.encode("您的验证码：8859【华信】","utf-8");
				String Text="【友惠家】验证码为：" + codeCont + ",请不要把验证码泄露给其他人,3分钟有效时间！";
				
				String Url="http://dx.ipyy.net/sms.aspx";
				
				HttpClient client=new HttpClient();
						
				PostMethod post=new PostMethod(Url);
				post.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
				NameValuePair userid=new NameValuePair("userid","53772");
				NameValuePair account=new NameValuePair("account","yhjapp");
				NameValuePair password=new NameValuePair("password","123456789");
				NameValuePair mobile=new NameValuePair("mobile",telphone);
				NameValuePair content=new NameValuePair("content",Text);
				NameValuePair sendTime=new NameValuePair("sendTime","");
				NameValuePair action=new NameValuePair("action","send");
				NameValuePair extno=new NameValuePair("extno","");
				post.setRequestBody(new NameValuePair[]{userid,account,password,mobile,content,sendTime,action,extno});
				int statu=client.executeMethod(post);
				System.out.println("statu="+statu);
				String str=post.getResponseBodyAsString();
				
				System.out.println(str);
				
//				HttpMethod method=new PostMethod(Url);//带参数的Url
//				method.setRequestHeader("Content-type", "text/xml; charset=utf-8");
//				client.executeMethod(method);
//				String str = method.getResponseBodyAsString();
//				System.out.println("result="+str);
				
				
					//将字符转化为XML
					Document doc=DocumentHelper.parseText(str);
					//获取根节点
					Element rootElt=doc.getRootElement();
					//获取根节点下的子节点的值
					String returnstatus=rootElt.elementText("returnstatus").trim();
					String message=rootElt.elementText("message").trim();
					String remainpoint=rootElt.elementText("remainpoint").trim();
					String taskID=rootElt.elementText("taskID").trim();
					String successCounts=rootElt.elementText("successCounts").trim();
					
					System.out.println("返回状态为"+returnstatus);
					System.out.println("返回信息提示："+message);
					System.out.println("返回余额："+remainpoint);
					System.out.println("返回任务批次："+taskID);
					System.out.println("返回成功条数："+successCounts);
					if(returnstatus.equals("Success")){
						result = SUCCESS;
					}else{
						result = FAIL;
					}
				} catch (Exception e) {
					
				}
				return result;
    }
    
    public String sendTixianMsg( String phone,String name,String money ){
    	String result = FAIL;
	    
		try {
		
		//String Text=URLEncoder.encode("您的验证码：8859【华信】","utf-8");
				String Text="【友惠家】温馨提醒：用户《" + name + "》申请提现"+money+"元到支付宝,请尽快处理！";
				
				String Url="http://dx.ipyy.net/sms.aspx";
				
				HttpClient client=new HttpClient();
						
				PostMethod post=new PostMethod(Url);
				post.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
				NameValuePair userid=new NameValuePair("userid","53772");
				NameValuePair account=new NameValuePair("account","yhjapp");
				NameValuePair password=new NameValuePair("password","123456789");
				NameValuePair mobile=new NameValuePair("mobile",phone);
				NameValuePair content=new NameValuePair("content",Text);
				NameValuePair sendTime=new NameValuePair("sendTime","");
				NameValuePair action=new NameValuePair("action","send");
				NameValuePair extno=new NameValuePair("extno","");
				post.setRequestBody(new NameValuePair[]{userid,account,password,mobile,content,sendTime,action,extno});
				int statu=client.executeMethod(post);
				System.out.println("statu="+statu);
				String str=post.getResponseBodyAsString();
				
				System.out.println(str);
				
//				HttpMethod method=new PostMethod(Url);//带参数的Url
//				method.setRequestHeader("Content-type", "text/xml; charset=utf-8");
//				client.executeMethod(method);
//				String str = method.getResponseBodyAsString();
//				System.out.println("result="+str);
				
				
					//将字符转化为XML
					Document doc=DocumentHelper.parseText(str);
					//获取根节点
					Element rootElt=doc.getRootElement();
					//获取根节点下的子节点的值
					String returnstatus=rootElt.elementText("returnstatus").trim();
					String message=rootElt.elementText("message").trim();
					String remainpoint=rootElt.elementText("remainpoint").trim();
					String taskID=rootElt.elementText("taskID").trim();
					String successCounts=rootElt.elementText("successCounts").trim();
					
					System.out.println("返回状态为"+returnstatus);
					System.out.println("返回信息提示："+message);
					System.out.println("返回余额："+remainpoint);
					System.out.println("返回任务批次："+taskID);
					System.out.println("返回成功条数："+successCounts);
					if(returnstatus.equals("Success")){
						result = SUCCESS;
					}else{
						result = FAIL;
					}
				} catch (Exception e) {
					
				}
				return result;
    }
    
    /**
     * 发送验证码通用方法（注册与修改密码需要用到）
     * @param telphone  手机号码
     * @return
     */
    public String sendMassage(String telphone){
    	    String result = null;
    	    //产生随机的验证码
         String codeCont = "";
 	    Random r = new Random();
 	    for(int i=0;i<6;i++){
 	    	codeCont += String.valueOf(r.nextInt(10));
 	    }
 	    
 	    PhoneCode phoneCode = new PhoneCode();
		phoneCode.setPhone(telphone);
		phoneCode.setCode(codeCont);
		phoneCode.setExpiredTime(getExpiredTimeCode(new Date()));
		
		String temp = phoneCodeService.add(phoneCode);
 	    
 	    if(ResponseCode.SUCCESS.getCode().equals(temp)){
 	    	HttpClient client = new HttpClient(); 
 			PostMethod method = new PostMethod(Url); 
 				
 			//client.getParams().setContentCharset("GBK");		
 			client.getParams().setContentCharset("UTF-8");
 			method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");

 		    //String content = new String("您的验证码是："+codeCont+"。请不要把验证码泄露给其他人。"); 
 		    String content = new String("您的验证码是：【"+codeCont+"】，3分钟有效时间，请不要把验证码泄露给其他人。");
 		    NameValuePair[] data = {//提交短信
 		    		 new NameValuePair("account", "C11714710"), 
  				     new NameValuePair("password", "85202a35086eb358e717dbf9ebc6e9bc"), //密码可以使用明文密码或使用32位MD5加密
 				    //new NameValuePair("account", "99911547"), 
				    //new NameValuePair("password", "a123456"), //密码可以使用明文密码或使用32位MD5加密
 				    //new NameValuePair("password", util.StringUtil.MD5Encode("密码")),
 				    new NameValuePair("mobile", telphone), 
 				    new NameValuePair("content", content),
 			};
 			
 			method.setRequestBody(data);		
 			
 			
 			try {
 				client.executeMethod(method);	
 				 
 				String SubmitResult =method.getResponseBodyAsString();
 						
 				//System.out.println(SubmitResult);

 				Document doc = DocumentHelper.parseText(SubmitResult); 
 				Element root = doc.getRootElement();


 				String code = root.elementText("code");	
 				//String msg = root.elementText("msg");	
 				//String smsid = root.elementText("smsid");	
 				
 				
 				//System.out.println(code);
 				//System.out.println(msg);
 				//System.out.println(smsid);
 							
 				if("2".equals(code)){
 					result = SUCCESS;
 				}
 				
 			} catch (Exception e) {
 				e.printStackTrace();
 			}	
 	    }
    	
 		return result;
    }
    
    /**
     * 发送邮件
     */
    public void sendMailMsg( String mail, String content ){
    	String host = "smtp.163.com";
    	String account = "18401762162@163.com";
    	String password = "Nizuibang521";
    	String byKey = sysSettingService.getByKey("SEND_MAIL_AND_PASSWORD_SET");
    	if( StringHelper.isNotBlank(byKey) ){
    		String[] split = byKey.split(",");
    		host = split[0];
    		account = split[1];
    		password = split[2];
    	}
    	Mail mailObj = new Mail(host, account, password, false);
    	String[] res = new String[1];
    	
    	res[0] = mail;
    	try {
			mailObj.doSendHtmlEmail("店主申请提现", content, res , null, null, null);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
    }
    
    
    /**
     * 重新过滤红包价格
     * @return
     */
    public String getHongbao( Product product ){
    	String result = "0";
    	boolean greater = DateHelper.isGreater(product.getStopTime()+" 23:59:59", DateHelper.formatDateTime(new Date()));
    	if( greater ){
    		result = product.getProductHongbao()+"";
    	}
    	return result;
    }
    
    public Double getHongbaoDouble( Product product ){
    	String result = "0";
    	boolean greater = DateHelper.isGreater(product.getStopTime()+" 23:59:59", DateHelper.formatDateTime(new Date()));
    	if( greater ){
    		result = product.getProductHongbao()+"";
    	}
    	return Double.parseDouble(result);
    }
    
    /**
     * 重新过滤红包价格
     * @return
     */
    public String getProdcutPrice( Product product ){
    	String result = "0";
    	boolean greater = DateHelper.isGreater(product.getStopTime()+" 23:59:59", DateHelper.formatDateTime(new Date()));
    	if( greater ){
    		result = product.getProductHongbao()+"";
    	}
    	result = NumberStringHelper.subtractString(product.getProductOrginPrice()+"",result);
    	return result;
    }
    
    public static String filterEmoji(String source) { 
    	String result = "";
        if(source != null)
        {
            Pattern emoji = Pattern.compile ("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",Pattern.UNICODE_CASE | Pattern . CASE_INSENSITIVE ) ;
            Matcher emojiMatcher = emoji.matcher(source);
            if ( emojiMatcher.find())
            {
                result = emojiMatcher.replaceAll("*");
            }
       }
       result = result.replace("*", "");
       result =result.replace(" ", "");
       return result; 
    }
    
    public void jdCountStatics( String userId, String returnStatus,String sku, String note ){
    	ProductJdStatisExample example = new ProductJdStatisExample();
    	com.itic.market.system.productjdstatis.persistence.model.ProductJdStatisExample.Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	//开始时间
    	String startStr = DateHelper.formatDate(new Date(), "yyyy-MM-dd");
    	startStr = startStr + " 00:00:00";
    	Date startTime = DateHelper.getDateByStringDate(startStr);
    	criteria.andCreateTimeBetween(startTime, new Date());
    	
    	int reorder = productJdStaticsService.count(example);
    	
    	ProductJdStatis statis = new ProductJdStatis();
    	statis.setReorder(reorder+1);
    	statis.setUserName(userId);
    	statis.setProductSku(sku);
    	statis.setReturnStatus(returnStatus);
    	statis.setNote(note);
    	productJdStaticsService.add(statis);
    }
    
    public String getTgwIdByTgwName( String tgwName ){
    	String result = "";
    	if( StringHelper.isNotBlank(tgwName) ){
    		SyncTgw temp = syncTgwService.getByTgwName(tgwName);
    		if( null != temp ){
    			result = temp.getTgwId();
    		}
    	}
    	return result;
    }
    
    
    /**
     * 获取推广位ID信息
     * @param userid
     * @return
     */
    public String getTgwidByUserid( String userid ){
    	String result = "";
    	if( StringHelper.isNotBlank(userid) ){
    		//根据用户获取推广位id
    		result = syncTgwService.getTgwidByUserid(userid);
    	}
    	return result;
    }
    
    /**
     * 根据推广位获取二合一转链接
     * @param userid
     * @param skuId
     * @param conUrlB
     * @return
     */
    public String getConUrl( String pid, String skuId, String conUrlB ){
    	String result = "";
    	if( StringHelper.isNotBlank(conUrlB) && StringHelper.isNotBlank(skuId) ){
    		result = productJdService.getConLinkByDdt(skuId,conUrlB,pid);
    	}
    	return result;
    }
    
    /**
     * 根据推广位获取二合一转链接
     * @param userid
     * @param skuId
     * @param conUrlB
     * @return
     */
    public String getCommonUrl( String pid, String skuId ){
    	String result = "";
    	if( StringHelper.isNotBlank(skuId) ){
    		result = productJdService.getCommonLinkByDdt( skuId,pid );
    	}
    	return result;
    }
    
    /**
     * @param goodsName //商品名称 
     * @param mainImageUrl 主图
     * @param oriPrice 原价
     * @param conPrice 券后价
     * @param couponMoney 红包券
     * @param totalSales 总销量
     * @param type   yh or jd
     * @param qcUrl  link
     * @return
     */
    public String getPoster( String goodsName, String mainImageUrl, String oriPrice,  String conPrice, String couponMoney, String totalSales, String type, String qcUrl ){
		String result = null;
		
		StringBuffer sb = new StringBuffer();
		//String url = "http://localhost:8090/image-server/uploadImage/oss/poster";
		String url = "http://file.jhjvip.cn:8888/image-server/uploadImage/oss/poster";
		
		sb.append("mainImageUrl=");
		sb.append(mainImageUrl);
		sb.append("&redPackage=");
		sb.append(couponMoney);
		sb.append("&preferentialPrice=");
		sb.append(conPrice);
		sb.append("&salesVolume=");
		sb.append(totalSales);
		sb.append("&originalPrice=");
		sb.append(oriPrice);
		sb.append("&productName=");
		goodsName = goodsName.replace("%", "百分比");
		sb.append(goodsName);
		sb.append("&type=");
		sb.append(type);
		sb.append("&url="+qcUrl);
		
		String sendPost = HttpRequestUtils.sendPost(url, sb.toString());
		JSONObject fromObject = JSONObject.fromObject(sendPost);
		String resultRemote = fromObject.getString("errorCode");
		if( "10000".equals(resultRemote)){
			result = fromObject.getString("data");
		}
		return result;
		
	}
    
}